<template>
  <view class="page">
    <!-- Tab栏 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ 
          active: activeTab === index && tab.type !== 'pickup',
          'pickup-tab': tab.type === 'pickup'
        }"
        @click="switchTab(index)"
      >
        <text class="tab-text">
          {{ tab.name || tab }}
          <text class="tab-icon" v-if="tab.type === 'pickup'">→</text>
        </text>
        <view class="tab-line" v-if="activeTab === index && tab.type !== 'pickup'"></view>
      </view>
    </view>

    <view class="search-box">
      <input class="search-input" v-model="keyword" placeholder="搜索订单号/地址/备注" confirm-type="search" @confirm="onSearch" />
      <view class="btn-search" @click="onSearch">搜索</view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="order-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="order-item" v-for="order in orderList" :key="order.id" @click="goToDetail(order)">
        <view class="order-header">
          <text class="order-no">订单号：{{ order.orderNo }}</text>
          <text class="order-status" :style="{ color: getStatusColor(order) }">
            {{ getStatusText(order) }}
          </text>
        </view>

        <view class="order-body">
          <view class="order-type-icon" :style="{ background: getTypeColor(order.type) }">
            <text class="type-emoji">{{ getTypeEmoji(order.type) }}</text>
          </view>
          <view class="order-info">
            <text class="order-title">{{ order.title }}</text>
            <text class="order-desc" v-if="(order.orderType || 1) === 1">{{ getGoodsSummary(order) }}</text>
            <text class="order-desc" v-else>{{ order.description }}</text>
            <text class="order-time">{{ order.createTime }}</text>
          </view>
        </view>

        <view class="order-footer">
          <view class="order-price">
            <text class="price-label">实付</text>
            <text class="price-value">¥{{ order.actualAmount }}</text>
          </view>
          <view class="order-actions">
            <!-- 待支付：取消订单 + 立即支付 -->
            <view class="btn btn-default" v-if="order.status === 0" @click.stop="cancelOrder(order)">取消订单</view>
            <view class="btn btn-primary" v-if="order.status === 0" @click.stop="payOrder(order)">立即支付</view>
            
            <!-- 配送中：确认收货 (status=3) -->
            <view class="btn btn-primary" v-if="order.status === 3" @click.stop="confirmReceive(order)">确认收货</view>
            
            <!-- 已完成：再来一单 (status=6) -->
            <view class="btn btn-default" v-if="order.status === 6 && (order.orderType || 1) === 1" @click.stop="buyAgain(order)">再来一单</view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="orderList.length === 0">
        <image class="empty-image" src="/static/images/empty-product.png" mode="aspectFit"></image>
        <text class="empty-text">暂无订单</text>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="orderList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getOrderStatusDisplay, getStatusColor, getOrderTypeText } from '@/utils/orderStatus'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      tabs: [
        { name: '全部', status: null },
        { name: '待支付', status: 0 },
        { name: '待接单', status: 1 },
        { name: '配送中', status: 3 },
        { name: '已完成', status: 6 },
        { name: '我的接单', type: 'pickup' }
      ],
      activeTab: 0,
      orderList: [],
      keyword: '',
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      finished: false
    }
  },
  computed: {
    ...mapGetters('user', ['userInfo']),
    // 当前登录用户ID
    currentUserId() {
      return this.userInfo?.id || ''
    },
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    }
  },
  onLoad() {
    this.checkUserRole()
  },
  onShow() {
    this.checkUserRole()
  },
  onPullDownRefresh() {
    this.page = 1
    this.finished = false
    this.orderList = []
    this.loadOrders()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 300)
  },
  methods: {
    checkUserRole() {
      // 商家角色显示提示，引导去"我的"页面
      if (this.$store.getters['user/userType'] === 3) {
        uni.showToast({
          title: '请在【我的】页面查看订单管理',
          icon: 'none',
          duration: 2000
        })
        
        // 延迟跳转到"我的"Tab页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/user/index'
          })
        }, 500)
        return
      }
      
      // 普通用户加载订单列表
      if (this.orderList.length === 0) {
        this.loadOrders()
      }
    },
    
    switchTab(index) {
      const selectedTab = this.tabs[index]
      
      // 如果是"我的接单"，跳转到接单页面
      if (selectedTab.type === 'pickup') {
        uni.navigateTo({
          url: '/pages/pickup/my-orders'
        })
        return
      }
      
      this.activeTab = index
      this.page = 1
      this.finished = false
      this.orderList = []
      this.loadOrders()
    },
    getGoodsSummary(order) {
      const items = Array.isArray(order?.items) ? order.items : []
      if (items.length === 0) return '—'
      const first = items[0]
      const more = items.length - 1
      const firstName = first.productName || first.name || '商品'
      return more > 0 ? `${firstName} 等${items.length}件商品` : firstName
    },
    onSearch() {
      this.page = 1
      this.finished = false
      this.orderList = []
      this.loadOrders()
    },
    async loadOrders() {
      if (this.loading || this.finished) return
      
      this.loading = true
      
      try {
        const { getOrderPage } = require('@/api/order')
        
        // 从当前选中的tab获取状态值
        const currentTab = this.tabs[this.activeTab]
        const status = currentTab.status
        const params = {
          current: this.page,
          size: this.pageSize
        }
        
        // 只有当status不为null时才添加到参数中
        if (status !== null) {
          params.status = status
        }
        if (this.keyword && this.keyword.trim()) {
          params.keyword = this.keyword.trim()
        }
        
        const pageData = await getOrderPage(params)
        
        //console.log('订单分页数据:', pageData)
        
        const records = pageData.records || []
        
        if (this.page === 1) {
          this.orderList = records
        } else {
          this.orderList.push(...records)
        }
        
        this.loading = false
        
        if (records.length < this.pageSize) {
          this.finished = true
        }
      } catch (error) {
        console.error('加载订单失败', error)
        this.loading = false
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadOrders()
    },
    getTypeEmoji(type) {
      const emojis = { 
        1: '🛒',  // 零食购买
        2: '📦',  // 取快递
        3: '🍔',  // 取外卖
        4: '☕'   // 代取奶咖
      }
      return emojis[type] || '📝'
    },
    getTypeColor(type) {
      const colors = {
        1: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
        2: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)',
        3: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
        4: 'linear-gradient(135deg, #d299c2 0%, #fef9d7 100%)'
      }
      return colors[type] || '#f5f5f5'
    },
    // 判断当前用户是否是订单的发布人
    isPublisher(order) {
      return order.userId && String(order.userId) === String(this.currentUserId)
    },
    
    // 获取显示的状态值（根据用户角色转换）
    getDisplayStatus(order) {
      const status = order.status
      const orderType = order.orderType || 1
      
      // 零食订单（orderType=1）不需要转换
      if (orderType === 1) {
        return status
      }
      
      // 代取订单（orderType=2,3,4）
      // 如果是发布人且status=5（待结算），显示为已完成(6)
      if (this.isPublisher(order) && status === 5) {
        return 6
      }
      
      return status
    },
    
    // 使用统一的状态管理工具
    getStatusText(order) {
      const orderType = order.orderType || 1
      const status = order.status ?? 0  // 确保 status 有值
      const displayStatus = this.getDisplayStatus(order)
      const display = getOrderStatusDisplay(orderType, displayStatus)
      
      // 调试输出
      if (display.text === '未知') {
        console.warn('未知订单状态:', { orderId: order.id, orderType, status: order.status, displayStatus })
      }
      
      return display.text
    },
    getStatusColor(order) {
      const orderType = order.orderType || 1
      const displayStatus = this.getDisplayStatus(order)
      return getStatusColor(orderType, displayStatus)
    },
    goToDetail(order) {
      const orderType = order.orderType || 1
      
      // 零食订单（orderType=1）跳转到零食订单详情页
      if (orderType === 1) {
        uni.navigateTo({
          url: `/pages/order/detail?id=${order.id}`
        })
      } else {
        // 代取订单（orderType=2,3,4）跳转到代取订单详情页
        uni.navigateTo({
          url: `/pages/pickup/detail?orderId=${order.id}`
        })
      }
    },
    cancelOrder(order) {
      uni.showModal({
        title: '提示',
        content: '确认取消订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const { cancelOrder } = require('@/api/order')
              await cancelOrder(order.id, '不想要了')
              uni.showToast({ title: '已取消', icon: 'success' })
              
              // 刷新列表
              this.page = 1
              this.finished = false
              this.loadOrders()
            } catch (error) {
              console.error('取消订单失败', error)
              uni.showToast({ title: (error && error.message) ? error.message : '取消失败', icon: 'none' })
            }
          }
        }
      })
    },
    payOrder(order) {
      // 跳转到支付页面（微信支付）
      uni.navigateTo({
        url: `/pages/order/payment?orderId=${order.id}&amount=${order.actualAmount}`
      })
    },
    confirmReceive(order) {
      uni.showModal({
        title: '确认收货',
        content: '确认已收到商品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const { confirmOrder } = require('@/api/order')
              await confirmOrder(order.id)
              uni.showToast({ title: '已确认收货', icon: 'success' })
              
              // 刷新列表
              this.page = 1
              this.finished = false
              this.orderList = []
              this.loadOrders()
            } catch (error) {
              console.error('确认收货失败', error)
              uni.showToast({ title: (error && error.message) ? error.message : '操作失败', icon: 'none' })
            }
          }
        }
      })
    },
    async buyAgain(order) {
      try {
        const orderType = order.orderType || 1
        if (orderType !== 1) {
          uni.showToast({ title: '该类型暂不支持再来一单', icon: 'none' })
          return
        }
        uni.showLoading({ title: '生成中...' })
        const { getReorderItems } = require('@/api/order')
        const list = await getReorderItems(order.id)
        uni.hideLoading()
        const items = Array.isArray(list) ? list : []
        if (items.length === 0) {
          uni.showToast({ title: '商品均已下架或无库存', icon: 'none' })
          return
        }
        const itemsParam = encodeURIComponent(JSON.stringify(items))
        uni.navigateTo({ url: `/pages/order/confirm?from=detail&items=${itemsParam}` })
      } catch (error) {
        console.error('再来一单失败:', error)
        uni.hideLoading()
        uni.showToast({ title: (error && error.message) ? error.message : '生成失败，请稍后再试', icon: 'none' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* Tab栏 */
.tabs {
  background: #fff;
  display: flex;
  padding: 0 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .tab-text {
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    
    .tab-icon {
      margin-left: 6rpx;
      font-size: 20rpx;
      color: #4ECDC4;
      font-weight: bold;
      transform: rotate(-45deg);
    }
  }
  
  .tab-line {
    position: absolute;
    bottom: 0;
    width: 40rpx;
    height: 6rpx;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    border-radius: 3rpx;
  }
  
  &.active .tab-text {
    color: #667eea;
    font-weight: bold;
  }
  
  &.pickup-tab {
    .tab-text {
      color: #4ECDC4;
      font-weight: 500;
      
      .tab-icon {
        animation: bounce 2s infinite;
      }
    }
    
    &:active {
      transform: scale(0.95);
      transition: transform 0.1s;
    }
  }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: rotate(-45deg) translateX(0);
  }
  40% {
    transform: rotate(-45deg) translateX(4rpx);
  }
  60% {
    transform: rotate(-45deg) translateX(2rpx);
  }
}

.search-box {
  display: flex;
  gap: 16rpx;
  padding: 20rpx;
  background: #fff;
}

.search-input {
  flex: 1;
  height: 72rpx;
  padding: 0 24rpx;
  border-radius: 36rpx;
  background: #f5f7fa;
  font-size: 26rpx;
}

.btn-search {
  width: 140rpx;
  height: 72rpx;
  border-radius: 36rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
}
/* 订单列表 */
.order-list {
  flex: 1;
  height: 0;
  padding: 20rpx;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}


.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .order-no {
    font-size: 24rpx;
    color: #999;
  }
  
  .order-status {
    font-size: 26rpx;
    font-weight: bold;
  }
}

.order-body {
  display: flex;
  gap: 20rpx;
  padding: 24rpx 0;
  
  .order-type-icon {
    width: 96rpx;
    height: 96rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    .type-emoji {
      font-size: 48rpx;
    }
  }
  
  .order-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    
    .order-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .order-desc {
      font-size: 24rpx;
      color: #999;
    }
    
    .order-time {
      font-size: 24rpx;
      color: #ccc;
    }
  }
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .order-price {
    display: flex;
    align-items: baseline;
    gap: 8rpx;
    
    .price-label {
      font-size: 24rpx;
      color: #999;
    }
    
    .price-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #ff6b6b;
    }
  }
  
  .order-actions {
    display: flex;
    gap: 16rpx;
  }
}

.btn {
  padding: 12rpx 28rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
  }
}

/* 空状态 */
.empty {
  padding: 120rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-image {
    width: 400rpx;
    height: 300rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 加载更多 */
.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>

